package jmine.tec.web.servlet.cipher.challenge;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import bancosys.tec.utils.md5sum.MD5SumTool;

/**
 * @author takeshi
 */
public class AssertionFactory implements Serializable {

    private static final int LAST_DIGIT = 94;

    private static final int FIRST_DIGIT = 32;

    private final int length;

    /**
     * C'tor
     * 
     * @param length int
     */
    public AssertionFactory(int length) {
        super();
        this.length = length;
    }

    /**
     * @return {@link Assertion}
     */
    public Assertion newAssertion() {
        Random rnd = new Random();
        byte[] array = new byte[length];
        for (int i = 0; i < length; i++) {
            array[i] = (byte) (FIRST_DIGIT + rnd.nextInt(LAST_DIGIT));
        }
        try {
            return new MD5Assertion(new String(array, "ASCII"));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("this system cannot use ASCII");
        }
    }

    /**
     * Implementacao simples de {@link Assertion} que usa um hash MD5
     * 
     * @author takeshi
     */
    private static class MD5Assertion implements Assertion {

        private final String question, md5;

        /**
         * C'tor
         * 
         * @param question {@link String}
         */
        public MD5Assertion(String question) {
            super();
            this.question = question;
            this.md5 = MD5SumTool.md5Sum(question);
        }

        /**
         * {@inheritDoc}
         */
        public String getExpected() {
            return md5;
        }

        /**
         * {@inheritDoc}
         */
        public String getQuestion() {
            return question;
        }

    }

}
